Q-3: Attempt the following (Any two) (10 Marks)
Questions
A: Describe the methods for working with Shapes in Android.
B: How can you manage Dates and Times in an Android application?
C: How can you use multiple layouts on a single screen?
Answer A: Methods for working with Shapes in Android
Android provides several methods to create and work with shapes in applications:
1. Drawable Shapes (XML)
Creating Shape Drawables:
<!-- res/drawable/circle_shape.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#FF5722" />
<stroke
android:width="2dp"
android:color="#000000" />
<size
android:width="100dp"
android:height="100dp" />
</shape>
<!-- res/drawable/rectangle_shape.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#2196F3" />
<corners android:radius="10dp" />
<stroke
android:width="1dp"
android:color="#1976D2" />
<gradient
android:startColor="#E3F2FD"
android:endColor="#2196F3"
android:angle="45" />
</shape>
Using Shape Drawables:
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/circle_shape" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rounded Button"
android:background="@drawable/rectangle_shape" />
2. Canvas and Paint (Programmatic)
public class ShapeView extends View {
private Paint paint;
public ShapeView(Context context) {
super(context);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw Circle
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(100, 100, 50, paint);
// Draw Rectangle
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
canvas.drawRect(50, 200, 150, 300, paint);
// Draw Line
paint.setColor(Color.GREEN);
canvas.drawLine(0, 350, 200, 350, paint);
// Draw Oval
paint.setColor(Color.YELLOW);
paint.setStyle(Paint.Style.FILL);
RectF oval = new RectF(50, 400, 150, 500);
canvas.drawOval(oval, paint);
// Draw Path (Custom Shape)
paint.setColor(Color.MAGENTA);
Path path = new Path();
path.moveTo(100, 550);
path.lineTo(150, 600);
path.lineTo(50, 600);
path.close();
canvas.drawPath(path, paint);
}
}
3. Vector Drawables
<!-- res/drawable/star_vector.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFD700"
android:pathData="M12,2l3.09,6.26L22,9.27l-5,4.87 1.18,6.88L12,17.77l-6.18,3.25L7,14.14 2,9.27l6.91-1.01L12,2Z" />
</vector>
4. Shape Types Available
- Rectangle:
android:shape="rectangle"
- Oval:
android:shape="oval"
- Line:
android:shape="line"
- Ring:
android:shape="ring"
5. Shape Attributes
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Solid Color -->
<solid android:color="#color" />
<!-- Gradient -->
<gradient
android:startColor="#color"
android:endColor="#color"
android:angle="45"
android:type="linear|radial|sweep" />
<!-- Stroke -->
<stroke
android:width="2dp"
android:color="#color"
android:dashWidth="4dp"
android:dashGap="2dp" />
<!-- Corners (for rectangle) -->
<corners
android:radius="10dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp" />
<!-- Size -->
<size
android:width="100dp"
android:height="100dp" />
<!-- Padding -->
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
Answer B: Managing Dates and Times in Android
Android provides several classes and methods to work with dates and times:
1. Date and Calendar Classes
// Using Date class
Date currentDate = new Date();
System.out.println("Current Date: " + currentDate);
// Using Calendar class
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
// Setting specific date
calendar.set(2024, Calendar.JANUARY, 15, 10, 30);
Date specificDate = calendar.getTime();
2. SimpleDateFormat for Formatting
// Format date to string
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
String formattedDate = formatter.format(new Date());
// Parse string to date
try {
Date parsedDate = formatter.parse("25/12/2024 10:30:00");
} catch (ParseException e) {
e.printStackTrace();
}
// Different format patterns
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2 = new SimpleDateFormat("MMM dd, yyyy");
SimpleDateFormat format3 = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
3. DatePicker and TimePicker
XML Layout:
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner" />
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner" />
Java Implementation:
DatePicker datePicker = findViewById(R.id.datePicker);
TimePicker timePicker = findViewById(R.id.timePicker);
// Get selected date
int year = datePicker.getYear();
int month = datePicker.getMonth();
int day = datePicker.getDayOfMonth();
// Get selected time
int hour = timePicker.getHour();
int minute = timePicker.getMinute();
// Set date programmatically
datePicker.updateDate(2024, 11, 25);
// Set time programmatically
timePicker.setHour(14);
timePicker.setMinute(30);
4. DatePickerDialog and TimePickerDialog
// DatePickerDialog
private void showDatePicker() {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(
this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
String date = selectedDay + "/" + (selectedMonth + 1) + "/" + selectedYear;
Toast.makeText(MainActivity.this, "Selected Date: " + date, Toast.LENGTH_SHORT).show();
}
},
year, month, day
);
datePickerDialog.show();
}
// TimePickerDialog
private void showTimePicker() {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(
this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
String time = selectedHour + ":" + selectedMinute;
Toast.makeText(MainActivity.this, "Selected Time: " + time, Toast.LENGTH_SHORT).show();
}
},
hour, minute, true // true for 24-hour format
);
timePickerDialog.show();
}
5. Modern Date/Time API (Android API 26+)
// Using LocalDate and LocalTime (API 26+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
LocalDateTime currentDateTime = LocalDateTime.now();
// Formatting
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
// Parsing
LocalDate parsedDate = LocalDate.parse("2024-12-25");
LocalTime parsedTime = LocalTime.parse("10:30:00");
}
6. Utility Methods
public class DateTimeUtils {
// Get current timestamp
public static long getCurrentTimestamp() {
return System.currentTimeMillis();
}
// Convert timestamp to readable date
public static String timestampToDate(long timestamp, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault());
return sdf.format(new Date(timestamp));
}
// Calculate age from birth date
public static int calculateAge(Date birthDate) {
Calendar birth = Calendar.getInstance();
birth.setTime(birthDate);
Calendar now = Calendar.getInstance();
int age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)) {
age--;
}
return age;
}
// Check if date is today
public static boolean isToday(Date date) {
Calendar today = Calendar.getInstance();
Calendar checkDate = Calendar.getInstance();
checkDate.setTime(date);
return today.get(Calendar.YEAR) == checkDate.get(Calendar.YEAR) &&
today.get(Calendar.DAY_OF_YEAR) == checkDate.get(Calendar.DAY_OF_YEAR);
}
// Add days to date
public static Date addDaysToDate(Date date, int days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, days);
return calendar.getTime();
}
}
Answer C: Using multiple layouts on a single screen
There are several ways to use multiple layouts on a single screen in Android:
1. Nested Layouts
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Header Layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#2196F3">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header"
android:layout_centerInParent="true"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</RelativeLayout>
<!-- Content Layout -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="16dp">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"
android:layout_marginEnd="8dp" />
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 2"
android:layout_marginStart="8dp" />
</LinearLayout>
</FrameLayout>
<!-- Footer Layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#4CAF50"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Footer"
android:textColor="#FFFFFF" />
</LinearLayout>
</LinearLayout>
2. Using ConstraintLayout (Recommended)
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Header Section -->
<LinearLayout
android:id="@+id/headerLayout"
android:layout_width="0dp"
android:layout_height="60dp"
android:background="#2196F3"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header Title"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</LinearLayout>
<!-- Left Panel -->
<RelativeLayout
android:id="@+id/leftPanel"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#E3F2FD"
android:layout_marginEnd="4dp"
app:layout_constraintTop_toBottomOf="@id/headerLayout"
app:layout_constraintBottom_toTopOf="@id/footerLayout"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@id/rightPanel"
app:layout_constraintWidth_percent="0.5">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Left Panel"
android:layout_centerInParent="true" />
</RelativeLayout>
<!-- Right Panel -->
<FrameLayout
android:id="@+id/rightPanel"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#F3E5F5"
android:layout_marginStart="4dp"
app:layout_constraintTop_toBottomOf="@id/headerLayout"
app:layout_constraintBottom_toTopOf="@id/footerLayout"
app:layout_constraintStart_toEndOf="@id/leftPanel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintWidth_percent="0.5">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right Button"
android:layout_gravity="center" />
</FrameLayout>
<!-- Footer Section -->
<LinearLayout
android:id="@+id/footerLayout"
android:layout_width="0dp"
android:layout_height="50dp"
android:background="#4CAF50"
android:gravity="center"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Footer"
android:textColor="#FFFFFF" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
3. Using Fragments for Multiple Layouts
Main Activity Layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/fragment_container_1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<FrameLayout
android:id="@+id/fragment_container_2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Load different fragments
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container_1, new TopFragment());
transaction.replace(R.id.fragment_container_2, new BottomFragment());
transaction.commit();
}
}
4. Using Include Tags
Create separate layout files:
header_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#2196F3"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Header"
android:textColor="#FFFFFF" />
</LinearLayout>
Main layout using include:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Include header -->
<include layout="@layout/header_layout" />
<!-- Main content area -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<!-- Content here -->
</RelativeLayout>
<!-- Include footer -->
<include layout="@layout/footer_layout" />
</LinearLayout>
5. Programmatic Layout Management
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create main container
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
// Create header layout
RelativeLayout headerLayout = new RelativeLayout(this);
headerLayout.setBackgroundColor(Color.BLUE);
LinearLayout.LayoutParams headerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 200);
TextView headerText = new TextView(this);
headerText.setText("Header");
headerText.setTextColor(Color.WHITE);
headerText.setGravity(Gravity.CENTER);
headerLayout.addView(headerText);
// Create content layout
FrameLayout contentLayout = new FrameLayout(this);
contentLayout.setBackgroundColor(Color.LTGRAY);
LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f);
// Add layouts to main container
mainLayout.addView(headerLayout, headerParams);
mainLayout.addView(contentLayout, contentParams);
setContentView(mainLayout);
}
}
Best Practices:
- Use ConstraintLayout for complex layouts to avoid deep nesting
- Avoid excessive nesting of layouts for better performance
- Use fragments for reusable UI components
- Use include tags for common layouts across multiple screens
- Consider ViewStub for layouts that are loaded conditionally
- Use merge tag to eliminate redundant layout wrappers